// src/api/mock.js
// Mock API 服务，用于在没有后端接口的情况下提供测试数据

import { generateBranchDataBatch } from '@/utils/branchDataGenerator.js';
import { generateMemberDataBatch } from '@/utils/memberDataGenerator.js';

// 生成初始数据
const mockBranches = generateBranchDataBatch(20);
const mockMembers = generateMemberDataBatch(100);

// 模拟网络延迟
const delay = (ms = 300) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟API响应格式
const createResponse = (data, total = null) => {
  if (total !== null) {
    return {
      list: data,
      total: total,
      page: 1,
      pageSize: 20
    };
  }
  return data;
};

// Mock API 函数
export const mockAPI = {
  // 党支部相关API
  branch: {
    // 获取党支部列表
    list: async (params = {}) => {
      await delay();
      
      let filteredBranches = [...mockBranches];
      
      // 搜索过滤
      if (params.search) {
        const searchTerm = params.search.toLowerCase();
        filteredBranches = filteredBranches.filter(branch => 
          branch.branchName.toLowerCase().includes(searchTerm) ||
          branch.branchDescription.toLowerCase().includes(searchTerm)
        );
      }
      
      // 类型过滤
      if (params.branchType) {
        filteredBranches = filteredBranches.filter(branch => 
          branch.branchType === params.branchType
        );
      }
      
      // 分页
      const page = params.page || 1;
      const pageSize = params.pageSize || 20;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedBranches = filteredBranches.slice(startIndex, endIndex);
      
      return createResponse(paginatedBranches, filteredBranches.length);
    },
    
    // 获取党支部详情
    detail: async (params) => {
      await delay();
      const branch = mockBranches.find(b => b.branchId === params.branchId);
      if (!branch) {
        throw new Error('党支部不存在');
      }
      return createResponse(branch);
    },
    
    // 创建党支部
    create: async (params) => {
      await delay();
      const newBranch = {
        ...generateBranchDataBatch(1)[0],
        ...params,
        branchId: `branch-${Date.now()}`
      };
      mockBranches.push(newBranch);
      return createResponse(newBranch);
    },
    
    // 更新党支部
    update: async (params) => {
      await delay();
      const index = mockBranches.findIndex(b => b.branchId === params.branchId);
      if (index === -1) {
        throw new Error('党支部不存在');
      }
      mockBranches[index] = { ...mockBranches[index], ...params.updateData };
      return createResponse(mockBranches[index]);
    },
    
    // 删除党支部
    delete: async (params) => {
      await delay();
      const index = mockBranches.findIndex(b => b.branchId === params.branchId);
      if (index === -1) {
        throw new Error('党支部不存在');
      }
      mockBranches.splice(index, 1);
      return createResponse({ success: true });
    },
    
    // 导出党支部数据
    exportData: async (params) => {
      await delay();
      const branch = mockBranches.find(b => b.branchId === params.branchId);
      if (!branch) {
        throw new Error('党支部不存在');
      }
      return createResponse({
        branchInfo: branch,
        exportTime: new Date().toISOString(),
        fileName: `党支部数据_${branch.branchName}_${new Date().toISOString().split('T')[0]}.json`
      });
    }
  },
  
  // 党员相关API
  member: {
    // 获取党员列表
    list: async (params = {}) => {
      await delay();
      
      let filteredMembers = [...mockMembers];
      
      // 搜索过滤
      if (params.search) {
        const searchTerm = params.search.toLowerCase();
        filteredMembers = filteredMembers.filter(member => 
          member.memberName.toLowerCase().includes(searchTerm) ||
          member.studentId.includes(searchTerm) ||
          member.phoneNumber.includes(searchTerm)
        );
      }
      
      // 分页
      const page = params.page || 1;
      const pageSize = params.pageSize || 20;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedMembers = filteredMembers.slice(startIndex, endIndex);
      
      return createResponse(paginatedMembers, filteredMembers.length);
    },
    
    // 获取党员详情
    detail: async (params) => {
      await delay();
      const member = mockMembers.find(m => m.id === params.memberId || m.memberId === params.memberId);
      if (!member) {
        throw new Error('党员不存在');
      }
      return createResponse(member);
    },
    
    // 创建党员
    create: async (params) => {
      await delay();
      const newMember = {
        ...generateMemberDataBatch(1)[0],
        ...params,
        id: `member-${Date.now()}`,
        memberId: `member-${Date.now()}`
      };
      mockMembers.push(newMember);
      return createResponse(newMember);
    },
    
    // 删除党员
    delete: async (params) => {
      await delay();
      const index = mockMembers.findIndex(m => m.id === params.memberId || m.memberId === params.memberId);
      if (index === -1) {
        throw new Error('党员不存在');
      }
      mockMembers.splice(index, 1);
      return createResponse({ success: true });
    },
    
    // 获取筛选选项
    filterOptions: async () => {
      await delay();
      return createResponse({
        politicalStatus: ['中共党员', '中共预备党员', '入党积极分子', '共青团员'],
        majors: ['计算机科学与技术', '软件工程', '信息管理与信息系统', '电子信息工程', '通信工程'],
        classes: ['计算机2101班', '计算机2102班', '软件2101班', '软件2102班', '信息2101班'],
        branches: [...new Set(mockMembers.map(m => m.currentPartyBranch))]
      });
    }
  }
};

// 导出所有成员的便捷函数
export const getAllMembers = async () => {
  return await mockAPI.member.list({ page: 1, pageSize: 1000 });
};

// 导出所有党支部的便捷函数
export const getAllBranches = async () => {
  return await mockAPI.branch.list({ page: 1, pageSize: 1000 });
};